import psutil
import time
import json
import requests
from datetime import datetime

class SystemMonitor:
    def __init__(self):
        self.metrics = []
    
    def collect_metrics(self):
        """收集系统指标"""
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        network = psutil.net_io_counters()
        
        # 进程信息
        processes = []
        for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
            if 'python' in proc.info['name'].lower():
                processes.append(proc.info)
        
        metric = {
            'timestamp': datetime.now().isoformat(),
            'cpu_percent': cpu_percent,
            'memory_percent': memory.percent,
            'memory_available': memory.available,
            'disk_percent': disk.percent,
            'network_sent': network.bytes_sent,
            'network_recv': network.bytes_recv,
            'python_processes': processes
        }
        
        return metric
    
    def monitor_during_test(self, duration=300):
        """测试期间监控"""
        print(f"开始监控系统性能，持续{duration}秒...")
        start_time = time.time()
        
        while time.time() - start_time < duration:
            metric = self.collect_metrics()
            self.metrics.append(metric)
            
            print(f"CPU: {metric['cpu_percent']:.1f}% | "
                  f"内存: {metric['memory_percent']:.1f}% | "
                  f"磁盘: {metric['disk_percent']:.1f}%")
            
            time.sleep(5)
        
        # 保存监控数据
        with open('monitoring_results.json', 'w') as f:
            json.dump(self.metrics, f, indent=2)
        
        print("监控完成，结果已保存到 monitoring_results.json")

if __name__ == "__main__":
    monitor = SystemMonitor()
    monitor.monitor_during_test(300)  # 监控5分钟